package com.hd123.rumba.request;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.buffalo.service.DefaultServiceRepository;
import net.buffalo.service.ServiceRepository;
import net.sf.hibernate.HibernateException;

import org.apache.log4j.Logger;

import com.hd123.rumba.runtime.Configuration;
import com.hd123.rumba.runtime.HibernateSession;
import com.hd123.rumba.user.IUser;
import com.hd123.rumba.util.StopWatch;

/**
 * @author caili
 */
public class BuffaloRequestHandler extends net.buffalo.web.servlet.ApplicationServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    process("get", request, response);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    process("post", request, response);
  }

  protected void process(String method, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Logger logger = Logger.getLogger(this.getClass());
    StopWatch sw = new StopWatch().start();
    String remoteHost = request.getRemoteHost();
    String requestURI = request.getRequestURI();
    String queryString = request.getQueryString();
    HttpSession session = request.getSession();
    String sessionId = session == null ? null : session.getId();
    String userId = null;

    BuffaloSession.setSession(session);
    try {
      try {
        IUser user = BuffaloSession.getCurrentUser();
        if (user != null)
          userId = user.getFullLogin();
      } catch (Exception e) {
      }
      if ("get".equals(method))
        super.doGet(request, response);
      else if ("post".equals(method))
        super.doPost(request, response);
    } catch (Throwable ex) {
      logger.error("", ex);
      if (ex instanceof ServletException)
        throw (ServletException) ex;
      if (ex instanceof IOException)
        throw (IOException) ex;
      throw new ServletException(ex);
    } finally {
      BuffaloSession.removeSession();
      try {
        HibernateSession.closeSession();
      } catch (HibernateException ex) {
        throw new ServletException(ex);
      }
    }

    logger.debug("perf|" + sw.stop() + "|" + remoteHost + ": " + method + " " + requestURI + "?"
        + queryString + " !@# " + sessionId + "|" + userId);
  }

  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
      List<String> buffaloFiles = Configuration.getInstance().getBuffaloList();
      if (buffaloFiles.size() > 0) {
        DefaultServiceRepository serviceRepository = (DefaultServiceRepository) getServletContext()
            .getAttribute(ServiceRepository.WEB_CONTEXT_KEY);
        for (int i = 0; i < buffaloFiles.size(); ++i) {
          String rn = buffaloFiles.get(i);
          Logger.getLogger(this.getClass()).info("装载Buffalo属性: " + rn);
          Properties prop = new Properties();
          prop.load(this.getClass().getResourceAsStream(rn));
          serviceRepository.registerAll(prop, "default");
          if (!prop.isEmpty()) {
            System.out.println(prop.toString());
          }
        }
      }
    } catch (Exception e) {
      Logger.getLogger(getClass()).error(e.getMessage());
      throw new ServletException(e);
    }
  }
}
